package cn.bs.seckill.service.impl;

import cn.bs.seckill.exception.GlobalException;
import cn.bs.seckill.mapper.UserMapper;

import cn.bs.seckill.pojo.User;
import cn.bs.seckill.service.UserService;
import cn.bs.seckill.utils.CookieUtil;
import cn.bs.seckill.utils.MD5Until;
import cn.bs.seckill.utils.RedisUtil;
import cn.bs.seckill.utils.UUIDUtil;
import cn.bs.seckill.vo.LoginVo;
import cn.bs.seckill.vo.RespBean;

import cn.bs.seckill.vo.RespBeanEnum;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService{
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserMapper userMapper;

    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {

        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

//        //判断密码账号是否为空
//        if (StringUtils.isEmpty(mobile)||
//        StringUtils.isEmpty(password)){
//            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
//
//        }
//
//        //判断是否正确输入手机号
//        if (!ValidatorUtil.isMobile(mobile)){
//            return RespBean.error(RespBeanEnum.LOGIN_FAILED);
//        }

        User user = userMapper.selectById(mobile);
        //判断手机号是否存在
//        if (null == user){
//          return   RespBean.error(RespBeanEnum.LOGIN_FAILED);
//        }

        if (null == user){
            throw new
                    GlobalException(RespBeanEnum.LOGIN_FAILED);
        }
        //判断密码是否正确

//        if (!(user.getPassword()).equals(MD5Until.toDBPassEpt(password))){
//
//            return RespBean.error(RespBeanEnum.LOGIN_FAILEDP);
//        }

        if (!(user.getPassword()).equals(MD5Until.toDBPassEpt(password))){
            throw new GlobalException
                    (RespBeanEnum.LOGIN_FAILEDP);
        }
//生成cookie
        String uuid = UUIDUtil.uuid();
        //把uuid和用户的登录信息存入session
//        request.getSession().setAttribute(uuid,user);
        //将用户信息存入redis
        redisUtil.set("user:"+uuid,user);

        //设置cook的值
        CookieUtil.setCookie(request, response, "userUUID", uuid);
        return RespBean.success();
    }

    @Override
    public User getUserByCookie(String userUUID) {
        if (StringUtils.isEmpty(userUUID)){
            return null;
        }
        //拿到用户信息
        User user =(User) redisUtil.get("user:" + userUUID);
        return user;
    }
}
